package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dto.UserDto;
import com.itheima.entry.PageResult;
import com.itheima.entry.QueryPageBean;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.RoleMenu;
import com.itheima.pojo.RoleUser;
import com.itheima.pojo.User;
import com.itheima.service.RoleUserService;
import com.itheima.service.UserService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;

import java.util.List;

/**
 * @author jshstart
 * @creat 2020-11-23 9:43
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Reference
    private RoleUserService roleUserService;
    @Override
    public PageResult queryAllByPage(QueryPageBean queryPageBean) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete",0);
        Page page=null;
        if (StringUtils.isEmpty(queryPageBean.getQueryString())){
            page=this.page(new Page<User>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize()),queryWrapper);
        }else {
            queryWrapper.and(wrapper->{
                wrapper.like("user_name",queryPageBean.getQueryString())
                        .or()
                        .like("real_name",queryPageBean.getQueryString());
            });
            page=this.page(new Page<User>(queryPageBean.getCurrentPage(),queryPageBean.getPageSize()),queryWrapper);
        }
     return new PageResult(page.getTotal(),page.getRecords());
    }

    @Override
    public void deleteById(Long id) {
        User user = new User();
        user.setId(id);
        user.setIsDelete(1);
        this.updateById(user);
    }

    @Override
    public void updateByUserName(User user) {
        this.baseMapper.updateByUserName(user);
    }

    @Override
    public List<User> findAllUser() {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("is_delete",0);
        List<User> list = this.list(queryWrapper);
        return list;
    }

    @Override
    public Long[] findRoleByRoleId(Long id) {
        return roleUserService.findRoleByRoleId(id);
    }

    @Override
    public boolean addRole(UserDto userDto) {
        Long userId = userDto.getUser().getId();
        Long[] roleIds = userDto.getRoleIds();
        roleUserService.deleteRoleByUserId(userId);
        if (roleIds!=null&&userId!=null){
            for (Long roleId : roleIds) {
                RoleUser roleUser = new RoleUser();
                roleUser.setUserId(userId);
                roleUser.setRoleId(roleId);
                roleUserService.saveOrUpdate(roleUser);
            }

        }
        return true;
    }

}
